package com.xiechuang.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.xiechuang.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description 控制层
 * @Author xiechuang
 * @Date 2021/11/9
 */
@RestController
@RequestMapping("")
public class TestController {

    @Autowired
    private TestService testService;
    @Autowired
    private LoadBalancerClient loadBalancerClient;

    /**
     * 测试访问
     *
     * @return
     */
    @RequestMapping("/test")
    public String testHello() {
        return "test success：eureka-client03-demo";
    }

    @RequestMapping("/testLoadBalance")
    public String testLoadBalance() {
        return testService.testLoadBalance();
    }

    @RequestMapping("/testRibbon")
    public String testRibbon() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client01-demo");
        return serviceInstance.getHost() + ":" + serviceInstance.getPort();
    }

    @RequestMapping("/testHystrix")
    @HystrixCommand(fallbackMethod = "testHystrixError")
    public String testHystrix() {
        ServiceInstance serviceInstance = loadBalancerClient.choose("eureka-client01-demo");
        return serviceInstance.getHost() + ":" + serviceInstance.getPort();
    }

    public String testHystrixError() {
        return "testHystrix sorry, error";
    }

}
